{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/Alvald1/HSE_colab/blob/main/001_Lic38_NumPy_(1).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fVecNv8IQ2tL"
      },
      "source": [
        "# Модуль NumPy\n",
        "\n",
        "NumPy - библиотека с открытым исходным кодом для языка программирования Python. \n",
        "\n",
        "Возможности: поддержка многомерных массивов; поддержка высокоуровневых математических функций, предназначенных для работы с многомерными массивами. [Википедия](https://ru.wikipedia.org/wiki/NumPy)\n",
        "\n",
        "https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises.md"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4_zYwQPrQ2tN"
      },
      "outputs": [],
      "source": [
        "import numpy as np # Негласно принятое сокращение"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a2Xj7VXWQ2tN",
        "outputId": "a70cb5cd-4f38-4794-9e92-34638b6fc652"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "['ALLOW_THREADS',\n",
              " 'AxisError',\n",
              " 'BUFSIZE',\n",
              " 'CLIP',\n",
              " 'ComplexWarning',\n",
              " 'DataSource',\n",
              " 'ERR_CALL',\n",
              " 'ERR_DEFAULT',\n",
              " 'ERR_IGNORE',\n",
              " 'ERR_LOG',\n",
              " 'ERR_PRINT',\n",
              " 'ERR_RAISE',\n",
              " 'ERR_WARN',\n",
              " 'FLOATING_POINT_SUPPORT',\n",
              " 'FPE_DIVIDEBYZERO',\n",
              " 'FPE_INVALID',\n",
              " 'FPE_OVERFLOW',\n",
              " 'FPE_UNDERFLOW',\n",
              " 'False_',\n",
              " 'Inf',\n",
              " 'Infinity',\n",
              " 'MAXDIMS',\n",
              " 'MAY_SHARE_BOUNDS',\n",
              " 'MAY_SHARE_EXACT',\n",
              " 'MachAr',\n",
              " 'ModuleDeprecationWarning',\n",
              " 'NAN',\n",
              " 'NINF',\n",
              " 'NZERO',\n",
              " 'NaN',\n",
              " 'PINF',\n",
              " 'PZERO',\n",
              " 'RAISE',\n",
              " 'RankWarning',\n",
              " 'SHIFT_DIVIDEBYZERO',\n",
              " 'SHIFT_INVALID',\n",
              " 'SHIFT_OVERFLOW',\n",
              " 'SHIFT_UNDERFLOW',\n",
              " 'ScalarType',\n",
              " 'Tester',\n",
              " 'TooHardError',\n",
              " 'True_',\n",
              " 'UFUNC_BUFSIZE_DEFAULT',\n",
              " 'UFUNC_PYVALS_NAME',\n",
              " 'VisibleDeprecationWarning',\n",
              " 'WRAP',\n",
              " '_NoValue',\n",
              " '_UFUNC_API',\n",
              " '__NUMPY_SETUP__',\n",
              " '__all__',\n",
              " '__builtins__',\n",
              " '__cached__',\n",
              " '__config__',\n",
              " '__doc__',\n",
              " '__file__',\n",
              " '__git_revision__',\n",
              " '__loader__',\n",
              " '__mkl_version__',\n",
              " '__name__',\n",
              " '__package__',\n",
              " '__path__',\n",
              " '__spec__',\n",
              " '__version__',\n",
              " '_add_newdoc_ufunc',\n",
              " '_arg',\n",
              " '_distributor_init',\n",
              " '_globals',\n",
              " '_mat',\n",
              " '_mklinit',\n",
              " '_pytesttester',\n",
              " 'abs',\n",
              " 'absolute',\n",
              " 'absolute_import',\n",
              " 'add',\n",
              " 'add_docstring',\n",
              " 'add_newdoc',\n",
              " 'add_newdoc_ufunc',\n",
              " 'alen',\n",
              " 'all',\n",
              " 'allclose',\n",
              " 'alltrue',\n",
              " 'amax',\n",
              " 'amin',\n",
              " 'angle',\n",
              " 'any',\n",
              " 'append',\n",
              " 'apply_along_axis',\n",
              " 'apply_over_axes',\n",
              " 'arange',\n",
              " 'arccos',\n",
              " 'arccosh',\n",
              " 'arcsin',\n",
              " 'arcsinh',\n",
              " 'arctan',\n",
              " 'arctan2',\n",
              " 'arctanh',\n",
              " 'argmax',\n",
              " 'argmin',\n",
              " 'argpartition',\n",
              " 'argsort',\n",
              " 'argwhere',\n",
              " 'around',\n",
              " 'array',\n",
              " 'array2string',\n",
              " 'array_equal',\n",
              " 'array_equiv',\n",
              " 'array_repr',\n",
              " 'array_split',\n",
              " 'array_str',\n",
              " 'asanyarray',\n",
              " 'asarray',\n",
              " 'asarray_chkfinite',\n",
              " 'ascontiguousarray',\n",
              " 'asfarray',\n",
              " 'asfortranarray',\n",
              " 'asmatrix',\n",
              " 'asscalar',\n",
              " 'atleast_1d',\n",
              " 'atleast_2d',\n",
              " 'atleast_3d',\n",
              " 'average',\n",
              " 'bartlett',\n",
              " 'base_repr',\n",
              " 'binary_repr',\n",
              " 'bincount',\n",
              " 'bitwise_and',\n",
              " 'bitwise_not',\n",
              " 'bitwise_or',\n",
              " 'bitwise_xor',\n",
              " 'blackman',\n",
              " 'block',\n",
              " 'bmat',\n",
              " 'bool',\n",
              " 'bool8',\n",
              " 'bool_',\n",
              " 'broadcast',\n",
              " 'broadcast_arrays',\n",
              " 'broadcast_to',\n",
              " 'busday_count',\n",
              " 'busday_offset',\n",
              " 'busdaycalendar',\n",
              " 'byte',\n",
              " 'byte_bounds',\n",
              " 'bytes0',\n",
              " 'bytes_',\n",
              " 'c_',\n",
              " 'can_cast',\n",
              " 'cast',\n",
              " 'cbrt',\n",
              " 'cdouble',\n",
              " 'ceil',\n",
              " 'cfloat',\n",
              " 'char',\n",
              " 'character',\n",
              " 'chararray',\n",
              " 'choose',\n",
              " 'clip',\n",
              " 'clongdouble',\n",
              " 'clongfloat',\n",
              " 'column_stack',\n",
              " 'common_type',\n",
              " 'compare_chararrays',\n",
              " 'compat',\n",
              " 'complex',\n",
              " 'complex128',\n",
              " 'complex64',\n",
              " 'complex_',\n",
              " 'complexfloating',\n",
              " 'compress',\n",
              " 'concatenate',\n",
              " 'conj',\n",
              " 'conjugate',\n",
              " 'convolve',\n",
              " 'copy',\n",
              " 'copysign',\n",
              " 'copyto',\n",
              " 'core',\n",
              " 'corrcoef',\n",
              " 'correlate',\n",
              " 'cos',\n",
              " 'cosh',\n",
              " 'count_nonzero',\n",
              " 'cov',\n",
              " 'cross',\n",
              " 'csingle',\n",
              " 'ctypeslib',\n",
              " 'cumprod',\n",
              " 'cumproduct',\n",
              " 'cumsum',\n",
              " 'datetime64',\n",
              " 'datetime_as_string',\n",
              " 'datetime_data',\n",
              " 'deg2rad',\n",
              " 'degrees',\n",
              " 'delete',\n",
              " 'deprecate',\n",
              " 'deprecate_with_doc',\n",
              " 'diag',\n",
              " 'diag_indices',\n",
              " 'diag_indices_from',\n",
              " 'diagflat',\n",
              " 'diagonal',\n",
              " 'diff',\n",
              " 'digitize',\n",
              " 'disp',\n",
              " 'divide',\n",
              " 'division',\n",
              " 'divmod',\n",
              " 'dot',\n",
              " 'double',\n",
              " 'dsplit',\n",
              " 'dstack',\n",
              " 'dtype',\n",
              " 'e',\n",
              " 'ediff1d',\n",
              " 'einsum',\n",
              " 'einsum_path',\n",
              " 'emath',\n",
              " 'empty',\n",
              " 'empty_like',\n",
              " 'equal',\n",
              " 'errstate',\n",
              " 'euler_gamma',\n",
              " 'exp',\n",
              " 'exp2',\n",
              " 'expand_dims',\n",
              " 'expm1',\n",
              " 'extract',\n",
              " 'eye',\n",
              " 'fabs',\n",
              " 'fastCopyAndTranspose',\n",
              " 'fft',\n",
              " 'fill_diagonal',\n",
              " 'find_common_type',\n",
              " 'finfo',\n",
              " 'fix',\n",
              " 'flatiter',\n",
              " 'flatnonzero',\n",
              " 'flexible',\n",
              " 'flip',\n",
              " 'fliplr',\n",
              " 'flipud',\n",
              " 'float',\n",
              " 'float16',\n",
              " 'float32',\n",
              " 'float64',\n",
              " 'float_',\n",
              " 'float_power',\n",
              " 'floating',\n",
              " 'floor',\n",
              " 'floor_divide',\n",
              " 'fmax',\n",
              " 'fmin',\n",
              " 'fmod',\n",
              " 'format_float_positional',\n",
              " 'format_float_scientific',\n",
              " 'format_parser',\n",
              " 'frexp',\n",
              " 'frombuffer',\n",
              " 'fromfile',\n",
              " 'fromfunction',\n",
              " 'fromiter',\n",
              " 'frompyfunc',\n",
              " 'fromregex',\n",
              " 'fromstring',\n",
              " 'full',\n",
              " 'full_like',\n",
              " 'fv',\n",
              " 'gcd',\n",
              " 'generic',\n",
              " 'genfromtxt',\n",
              " 'geomspace',\n",
              " 'get_array_wrap',\n",
              " 'get_include',\n",
              " 'get_printoptions',\n",
              " 'getbufsize',\n",
              " 'geterr',\n",
              " 'geterrcall',\n",
              " 'geterrobj',\n",
              " 'gradient',\n",
              " 'greater',\n",
              " 'greater_equal',\n",
              " 'half',\n",
              " 'hamming',\n",
              " 'hanning',\n",
              " 'heaviside',\n",
              " 'histogram',\n",
              " 'histogram2d',\n",
              " 'histogram_bin_edges',\n",
              " 'histogramdd',\n",
              " 'hsplit',\n",
              " 'hstack',\n",
              " 'hypot',\n",
              " 'i0',\n",
              " 'identity',\n",
              " 'iinfo',\n",
              " 'imag',\n",
              " 'in1d',\n",
              " 'index_exp',\n",
              " 'indices',\n",
              " 'inexact',\n",
              " 'inf',\n",
              " 'info',\n",
              " 'infty',\n",
              " 'inner',\n",
              " 'insert',\n",
              " 'int',\n",
              " 'int0',\n",
              " 'int16',\n",
              " 'int32',\n",
              " 'int64',\n",
              " 'int8',\n",
              " 'int_',\n",
              " 'int_asbuffer',\n",
              " 'intc',\n",
              " 'integer',\n",
              " 'interp',\n",
              " 'intersect1d',\n",
              " 'intp',\n",
              " 'invert',\n",
              " 'ipmt',\n",
              " 'irr',\n",
              " 'is_busday',\n",
              " 'isclose',\n",
              " 'iscomplex',\n",
              " 'iscomplexobj',\n",
              " 'isfinite',\n",
              " 'isfortran',\n",
              " 'isin',\n",
              " 'isinf',\n",
              " 'isnan',\n",
              " 'isnat',\n",
              " 'isneginf',\n",
              " 'isposinf',\n",
              " 'isreal',\n",
              " 'isrealobj',\n",
              " 'isscalar',\n",
              " 'issctype',\n",
              " 'issubclass_',\n",
              " 'issubdtype',\n",
              " 'issubsctype',\n",
              " 'iterable',\n",
              " 'ix_',\n",
              " 'kaiser',\n",
              " 'kron',\n",
              " 'lcm',\n",
              " 'ldexp',\n",
              " 'left_shift',\n",
              " 'less',\n",
              " 'less_equal',\n",
              " 'lexsort',\n",
              " 'lib',\n",
              " 'linalg',\n",
              " 'linspace',\n",
              " 'little_endian',\n",
              " 'load',\n",
              " 'loads',\n",
              " 'loadtxt',\n",
              " 'log',\n",
              " 'log10',\n",
              " 'log1p',\n",
              " 'log2',\n",
              " 'logaddexp',\n",
              " 'logaddexp2',\n",
              " 'logical_and',\n",
              " 'logical_not',\n",
              " 'logical_or',\n",
              " 'logical_xor',\n",
              " 'logspace',\n",
              " 'long',\n",
              " 'longcomplex',\n",
              " 'longdouble',\n",
              " 'longfloat',\n",
              " 'longlong',\n",
              " 'lookfor',\n",
              " 'ma',\n",
              " 'mafromtxt',\n",
              " 'mask_indices',\n",
              " 'mat',\n",
              " 'math',\n",
              " 'matmul',\n",
              " 'matrix',\n",
              " 'matrixlib',\n",
              " 'max',\n",
              " 'maximum',\n",
              " 'maximum_sctype',\n",
              " 'may_share_memory',\n",
              " 'mean',\n",
              " 'median',\n",
              " 'memmap',\n",
              " 'meshgrid',\n",
              " 'mgrid',\n",
              " 'min',\n",
              " 'min_scalar_type',\n",
              " 'minimum',\n",
              " 'mintypecode',\n",
              " 'mirr',\n",
              " 'mod',\n",
              " 'modf',\n",
              " 'moveaxis',\n",
              " 'msort',\n",
              " 'multiply',\n",
              " 'nan',\n",
              " 'nan_to_num',\n",
              " 'nanargmax',\n",
              " 'nanargmin',\n",
              " 'nancumprod',\n",
              " 'nancumsum',\n",
              " 'nanmax',\n",
              " 'nanmean',\n",
              " 'nanmedian',\n",
              " 'nanmin',\n",
              " 'nanpercentile',\n",
              " 'nanprod',\n",
              " 'nanquantile',\n",
              " 'nanstd',\n",
              " 'nansum',\n",
              " 'nanvar',\n",
              " 'nbytes',\n",
              " 'ndarray',\n",
              " 'ndenumerate',\n",
              " 'ndfromtxt',\n",
              " 'ndim',\n",
              " 'ndindex',\n",
              " 'nditer',\n",
              " 'negative',\n",
              " 'nested_iters',\n",
              " 'newaxis',\n",
              " 'nextafter',\n",
              " 'nonzero',\n",
              " 'not_equal',\n",
              " 'nper',\n",
              " 'npv',\n",
              " 'numarray',\n",
              " 'number',\n",
              " 'obj2sctype',\n",
              " 'object',\n",
              " 'object0',\n",
              " 'object_',\n",
              " 'ogrid',\n",
              " 'oldnumeric',\n",
              " 'ones',\n",
              " 'ones_like',\n",
              " 'outer',\n",
              " 'packbits',\n",
              " 'pad',\n",
              " 'partition',\n",
              " 'percentile',\n",
              " 'pi',\n",
              " 'piecewise',\n",
              " 'place',\n",
              " 'pmt',\n",
              " 'poly',\n",
              " 'poly1d',\n",
              " 'polyadd',\n",
              " 'polyder',\n",
              " 'polydiv',\n",
              " 'polyfit',\n",
              " 'polyint',\n",
              " 'polymul',\n",
              " 'polynomial',\n",
              " 'polysub',\n",
              " 'polyval',\n",
              " 'positive',\n",
              " 'power',\n",
              " 'ppmt',\n",
              " 'print_function',\n",
              " 'printoptions',\n",
              " 'prod',\n",
              " 'product',\n",
              " 'promote_types',\n",
              " 'ptp',\n",
              " 'put',\n",
              " 'put_along_axis',\n",
              " 'putmask',\n",
              " 'pv',\n",
              " 'quantile',\n",
              " 'r_',\n",
              " 'rad2deg',\n",
              " 'radians',\n",
              " 'random',\n",
              " 'rank',\n",
              " 'rate',\n",
              " 'ravel',\n",
              " 'ravel_multi_index',\n",
              " 'real',\n",
              " 'real_if_close',\n",
              " 'rec',\n",
              " 'recarray',\n",
              " 'recfromcsv',\n",
              " 'recfromtxt',\n",
              " 'reciprocal',\n",
              " 'record',\n",
              " 'remainder',\n",
              " 'repeat',\n",
              " 'require',\n",
              " 'reshape',\n",
              " 'resize',\n",
              " 'result_type',\n",
              " 'right_shift',\n",
              " 'rint',\n",
              " 'roll',\n",
              " 'rollaxis',\n",
              " 'roots',\n",
              " 'rot90',\n",
              " 'round',\n",
              " 'round_',\n",
              " 'row_stack',\n",
              " 's_',\n",
              " 'safe_eval',\n",
              " 'save',\n",
              " 'savetxt',\n",
              " 'savez',\n",
              " 'savez_compressed',\n",
              " 'sctype2char',\n",
              " 'sctypeDict',\n",
              " 'sctypeNA',\n",
              " 'sctypes',\n",
              " 'searchsorted',\n",
              " 'select',\n",
              " 'set_numeric_ops',\n",
              " 'set_printoptions',\n",
              " 'set_string_function',\n",
              " 'setbufsize',\n",
              " 'setdiff1d',\n",
              " 'seterr',\n",
              " 'seterrcall',\n",
              " 'seterrobj',\n",
              " 'setxor1d',\n",
              " 'shape',\n",
              " 'shares_memory',\n",
              " 'short',\n",
              " 'show_config',\n",
              " 'sign',\n",
              " 'signbit',\n",
              " 'signedinteger',\n",
              " 'sin',\n",
              " 'sinc',\n",
              " 'single',\n",
              " 'singlecomplex',\n",
              " 'sinh',\n",
              " 'size',\n",
              " 'sometrue',\n",
              " 'sort',\n",
              " 'sort_complex',\n",
              " 'source',\n",
              " 'spacing',\n",
              " 'split',\n",
              " 'sqrt',\n",
              " 'square',\n",
              " 'squeeze',\n",
              " 'stack',\n",
              " 'std',\n",
              " 'str',\n",
              " 'str0',\n",
              " 'str_',\n",
              " 'string_',\n",
              " 'subtract',\n",
              " 'sum',\n",
              " 'swapaxes',\n",
              " 'sys',\n",
              " 'take',\n",
              " 'take_along_axis',\n",
              " 'tan',\n",
              " 'tanh',\n",
              " 'tensordot',\n",
              " 'test',\n",
              " 'testing',\n",
              " 'tile',\n",
              " 'timedelta64',\n",
              " 'trace',\n",
              " 'tracemalloc_domain',\n",
              " 'transpose',\n",
              " 'trapz',\n",
              " 'tri',\n",
              " 'tril',\n",
              " 'tril_indices',\n",
              " 'tril_indices_from',\n",
              " 'trim_zeros',\n",
              " 'triu',\n",
              " 'triu_indices',\n",
              " 'triu_indices_from',\n",
              " 'true_divide',\n",
              " 'trunc',\n",
              " 'typeDict',\n",
              " 'typeNA',\n",
              " 'typecodes',\n",
              " 'typename',\n",
              " 'ubyte',\n",
              " 'ufunc',\n",
              " 'uint',\n",
              " 'uint0',\n",
              " 'uint16',\n",
              " 'uint32',\n",
              " 'uint64',\n",
              " 'uint8',\n",
              " 'uintc',\n",
              " 'uintp',\n",
              " 'ulonglong',\n",
              " 'unicode',\n",
              " 'unicode_',\n",
              " 'union1d',\n",
              " 'unique',\n",
              " 'unpackbits',\n",
              " 'unravel_index',\n",
              " 'unsignedinteger',\n",
              " 'unwrap',\n",
              " 'ushort',\n",
              " 'vander',\n",
              " 'var',\n",
              " 'vdot',\n",
              " 'vectorize',\n",
              " 'version',\n",
              " 'void',\n",
              " 'void0',\n",
              " 'vsplit',\n",
              " 'vstack',\n",
              " 'warnings',\n",
              " 'where',\n",
              " 'who',\n",
              " 'zeros',\n",
              " 'zeros_like']"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "dir(np)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0zNupqn-Q2tO"
      },
      "source": [
        "## ndarray\n",
        "\n",
        "Основным объектом NumPy является однородный многомерный массив (в numpy называется numpy.ndarray). Это многомерный массив элементов (обычно чисел), одного типа.\n",
        "\n",
        "```\n",
        "ndarray(shape, dtype=float, buffer=None, offset=0,\n",
        "        strides=None, order=None)\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tI7Rv3j9Q2tP"
      },
      "source": [
        "`shape` - размерность массива, кортеж натуральных чисел, показывающий длину массива по каждой оси."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HWXMUQzZQ2tP",
        "outputId": "bb77962f-7489-4a4c-dff9-588b7cc4b66e"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(array([0, 0, 0, 0]), (4,))"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "Data = np.ndarray((4,),dtype = int)\n",
        "Data, Data.shape"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "K8HHcs9VQ2tP"
      },
      "source": [
        "`dtype` -  тип элементов, можно использовать встроенные, или типы из numpy:\n",
        "\n",
        "` bool_, character, int_, int8, int16, int32, int64, float16, float32, float64, complex64, object_.`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JQhPLJrRQ2tP"
      },
      "outputs": [],
      "source": [
        "# Двумерный массив - матрица\n",
        "A = np.ndarray((3,4), dtype = np.float16)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UwLIZpR_Q2tQ"
      },
      "outputs": [],
      "source": [
        "A[1,1]=111"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mwFMj54xQ2tQ",
        "outputId": "f589260f-7434-478d-f845-f4c4385b94a3"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[  0.   0.   0.   0.]\n",
            " [  0. 111.   0.   0.]\n",
            " [  0.   0.   0.   0.]]\n"
          ]
        }
      ],
      "source": [
        "print(A)# Заполняется мусором из памяти"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S7mUKYogQ2tQ"
      },
      "source": [
        "## Создание массивов"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yXX9NfdLQ2tQ"
      },
      "source": [
        "### Массив из нулей, единиц, единичная матрица"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "u6dRcI6eQ2tR",
        "outputId": "adf720b7-b1eb-4e58-c649-8824c6ddac82"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[0, 0, 0, 0],\n",
              "       [0, 0, 0, 0]])"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.zeros((2,4), dtype=int)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ghubg1kYQ2tR",
        "outputId": "2c18362c-5f6c-4d94-ac2e-51a1306f1b48"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([1., 1., 1., 1., 1.], dtype=float16)"
            ]
          },
          "execution_count": 9,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.ones((5,), dtype=np.float16)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LnyuGmtuQ2tR",
        "outputId": "00cb45a2-3707-48ae-f83e-7d6985f1b51e"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[1., 0., 0.],\n",
              "       [0., 1., 0.],\n",
              "       [0., 0., 1.]])"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.eye(3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ogmmd9C-Q2tR",
        "outputId": "96485128-0841-4e32-cc88-7f1292e5eb4f"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[0., 0., 1., 0., 0., 0.],\n",
              "       [0., 0., 0., 1., 0., 0.],\n",
              "       [0., 0., 0., 0., 1., 0.]])"
            ]
          },
          "execution_count": 11,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.eye(3,6,2)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_kgOZukfQ2tS",
        "outputId": "766c853c-8fba-4791-c51c-218e5aa5e490"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "numpy.ndarray"
            ]
          },
          "execution_count": 12,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "type(np.eye(3))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JNwDALBwQ2tS",
        "outputId": "02d33969-7065-4554-b3b4-57956501d1fb"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[0., 0., 0., 0., 0.],\n",
              "       [0., 0., 0., 0., 0.],\n",
              "       [0., 0., 0., 0., 0.]])"
            ]
          },
          "execution_count": 13,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.empty((3, 5)) #?????"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r3GxBNU1Q2tS"
      },
      "source": [
        "### Другие способы создания\n",
        "\n",
        "`numpy.array()` - функция, создающая объект типа `ndarray`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JBNcSiQ7Q2tS",
        "outputId": "c5caa8e2-d861-4f16-f60f-249d849e3dc4"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(array([[1, 2, 3],\n",
              "        [5, 6, 7]]), numpy.ndarray)"
            ]
          },
          "execution_count": 14,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "a = np.array([[1,2,3],[5,6,7]])\n",
        "a, type(a)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZldS5qpdQ2tT",
        "outputId": "697d5e76-e76a-429f-cdb0-45fcd4f25d1e"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81],\n",
              "       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1],\n",
              "       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3]])"
            ]
          },
          "execution_count": 15,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b =  np.array([[x*x for x in range(10)],[1]*10,[3]*10])\n",
        "b"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hmzddQsVQ2tT"
      },
      "source": [
        "### Функции arange, linspace, fromfunction"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JsaSO_5mQ2tT",
        "outputId": "1ade5167-d42f-4732-deb7-dc9b5394f55d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[0 1 2 3 4 5 6 7 8 9]\n",
            "[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]\n",
            "[[0.  1.  2.  3.  4.  5.  6.  7.  8.  9. ]\n",
            " [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]]\n"
          ]
        }
      ],
      "source": [
        "print(np.arange(10), \n",
        "      np.arange(0, 1, 0.1),\n",
        "      np.array([np.arange(10), np.arange(0, 1, 0.1)]),sep='\\n')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "D0U0SnIoQ2tT",
        "outputId": "f19de981-ad59-4101-92c3-be9af45fb194"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([0.  , 0.25, 0.5 , 0.75, 1.  ])"
            ]
          },
          "execution_count": 17,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# В отличии от arange можно точно указать количество элементов\n",
        "np.linspace(0, 1, 5)  # 5 чисел от 0 до 1 включительно"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xfB-x50rQ2tU",
        "outputId": "5d27804b-23f7-4c74-cd4e-0f36471bb954"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ True, False,  True],\n",
              "       [False,  True, False],\n",
              "       [ True, False,  True]])"
            ]
          },
          "execution_count": 18,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# def fun(i,j):\n",
        "#     return (i + j) % 2 == 0\n",
        "\n",
        "np.fromfunction(lambda i,j: (i + j) % 2 == 0, (3, 3), dtype=int)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "muUyXNhCQ2tU"
      },
      "source": [
        "**Пример**. Создание массива пользовательского типа,в виде сетки точек на плоскости с координатами из отрезка $[0, 1]$.\n",
        "\n",
        "https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MCDVTSNlQ2tU",
        "outputId": "692117bc-f6ac-4280-c58c-e15ef09d6c3e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[(0.  , 0.  ) (0.25, 0.  ) (0.5 , 0.  ) (0.75, 0.  ) (1.  , 0.  )]\n",
            " [(0.  , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1.  , 0.25)]\n",
            " [(0.  , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1.  , 0.5 )]\n",
            " [(0.  , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1.  , 0.75)]\n",
            " [(0.  , 1.  ) (0.25, 1.  ) (0.5 , 1.  ) (0.75, 1.  ) (1.  , 1.  )]] [('x', '<f8'), ('y', '<f8')]\n"
          ]
        }
      ],
      "source": [
        "Z = np.zeros((5,5), [('x',float),('y',float)])\n",
        "Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),np.linspace(0,1,5))\n",
        "print(Z, np.dtype(Z[1,1]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i4N8bsQ2Q2tU"
      },
      "source": [
        "## Изменение формы массива:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EVME3BPqQ2tV",
        "outputId": "8072f8a8-965b-46a3-e642-1df9ae3b8106"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(9,)"
            ]
          },
          "execution_count": 20,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "a = np.arange(1,10)\n",
        "a.shape"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nXStu01nQ2tV",
        "outputId": "5ca618cd-9a5d-4a41-e358-d8e341b35d16"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[1, 2, 3],\n",
              "       [4, 5, 6],\n",
              "       [7, 8, 9]])"
            ]
          },
          "execution_count": 21,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "a.reshape(3,3)  #  [:,1]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Cnt1UDV2Q2tV",
        "outputId": "74bd8a97-31fa-421a-fa90-f5cc71aa3307"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(array([1, 2, 3, 4, 5, 6, 7, 8, 9]), (9,))"
            ]
          },
          "execution_count": 22,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "a, a.shape"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BF8w1EjHQ2tV"
      },
      "outputs": [],
      "source": [
        "a.shape = (3,3)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SPLu3R4dQ2tV",
        "outputId": "a97799bf-8315-4c04-9598-d206b50784f9"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(array([[1, 2, 3],\n",
              "        [4, 5, 6],\n",
              "        [7, 8, 9]]), (3, 3))"
            ]
          },
          "execution_count": 24,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "a, a.shape"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uzpHmihVQ2tW"
      },
      "source": [
        "## Срезы ndarray\n",
        "\n",
        "Для одномерных массивов аналогично спискам:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-0Adv5iwQ2tW",
        "outputId": "0d72d976-9cd2-43cd-8eb7-55cbea05e404"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(array([1, 2, 3, 4]), array([5, 6, 7, 8, 9]))"
            ]
          },
          "execution_count": 25,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "a = np.arange(1,10)\n",
        "a[:4], a[4:]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PGWD2XXhQ2tW"
      },
      "source": [
        "Многомерные масивы:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iYx2pNttQ2tW",
        "outputId": "3c4d3ab9-3fb2-44f2-8e1a-be9a671753df"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[2, 4, 2, 1],\n",
              "       [3, 2, 1, 1],\n",
              "       [2, 3, 2, 4]])"
            ]
          },
          "execution_count": 26,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Матрица из случайных чисел от 0 до 4 включительно размера 3 на 4\n",
        "data = np.random.randint(0, 5, (3, 4))\n",
        "data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qpeIBazVQ2tX",
        "outputId": "3a70674e-2226-4860-c01b-4726dc925787"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(array([2, 3, 2, 4]), array([2, 3, 2, 4]), array([2, 3, 2, 4]))"
            ]
          },
          "execution_count": 27,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "data[2], data[2,:], data[2, 0:4]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ERcNcI5xQ2tX",
        "outputId": "9a76b9c2-58cc-4ce5-9e98-d686ce0e5ae8"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[4, 2, 1],\n",
              "       [2, 1, 1],\n",
              "       [3, 2, 4]])"
            ]
          },
          "execution_count": 28,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "data[:,1:] # без первого столбца"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MmJGh-YoQ2tX"
      },
      "source": [
        "Срез как представление данных, позволяет изменить часть массива:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yvFe_t-EQ2tX",
        "outputId": "286f8d70-c285-4c00-8c22-15c2ee6fec0c"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 2,  4,  2, 99],\n",
              "       [ 3,  2,  1, 99],\n",
              "       [ 2,  3,  2, 99]])"
            ]
          },
          "execution_count": 29,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "data[:,3] = 99\n",
        "data"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ODEabMbKQ2tX"
      },
      "source": [
        "## Операции с массивами"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q3WJFyJsQ2tX"
      },
      "source": [
        "Арифметические операции:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "voCuG2wRQ2tY",
        "outputId": "69379dd7-f9e0-4f1e-cd04-45db3e9d9b82"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[2 2 2 2] [0 1 2 3]\n"
          ]
        }
      ],
      "source": [
        "a = np.array([2]*4)\n",
        "b = np.arange(4)\n",
        "print(a,b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GQ3kPy-WQ2tY",
        "outputId": "900fd4b2-74cf-447d-9eca-b82ea263264a"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[2 3 4 5]\n",
            "[ 2  1  0 -1]\n",
            "[0 2 4 6]\n",
            "[       inf 2.         1.         0.66666667]\n",
            "[0 0 0 2]\n",
            "[1 2 4 8]\n"
          ]
        },
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "C:\\Users\\Artem\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in true_divide\n",
            "  \"\"\"\n",
            "C:\\Users\\Artem\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:6: RuntimeWarning: divide by zero encountered in remainder\n",
            "  \n"
          ]
        }
      ],
      "source": [
        "print(\n",
        "a + b,\n",
        "a - b,\n",
        "a * b,\n",
        "a / b,\n",
        "a % b,\n",
        "a ** b,\n",
        "sep='\\n')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nfiJsFjuQ2tY",
        "outputId": "7db68753-d471-462a-e39b-9dbf44183536"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([0, 2, 4, 6])"
            ]
          },
          "execution_count": 32,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b * 2"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "k28ccsLtQ2tY",
        "outputId": "b4c21706-1ead-47ce-88ef-432e1bb44a2d"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([3, 4, 5, 6])"
            ]
          },
          "execution_count": 33,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b + 3"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8x_FgPVVQ2tY",
        "outputId": "e9dc2131-274e-4262-ebff-2196c609874e"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([0, 1, 4, 9], dtype=int32)"
            ]
          },
          "execution_count": 34,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b**2"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SDj_5LrdQ2tZ"
      },
      "source": [
        "### Математические функции NumPy:\n",
        "\n",
        "https://docs.scipy.org/doc/numpy/reference/routines.math.html"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "itXFvEMxQ2tZ",
        "outputId": "ce289f80-ba69-4e51-d1e0-d292067c3a5f"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([ 1.        ,  0.54030231, -0.41614684, -0.9899925 ])"
            ]
          },
          "execution_count": 35,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.cos(b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EcXHy6tRQ2tZ",
        "outputId": "6bed2c6e-27ec-424e-a12d-82e5f764631d"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([ 1.        ,  2.71828183,  7.3890561 , 20.08553692])"
            ]
          },
          "execution_count": 36,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.exp(b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rIAvqf0PQ2tZ",
        "outputId": "4fa99edc-d6b6-462e-867a-733e3924d622"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "6"
            ]
          },
          "execution_count": 37,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.sum(b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sIVzKWRqQ2tZ",
        "outputId": "1c254f86-c99f-4558-a13d-67b6f04cadd1"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([3, 2, 5])"
            ]
          },
          "execution_count": 38,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.array([3,2,5]).T"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "j94OeawlQ2tZ",
        "outputId": "8ef6596b-b24d-4dc6-9541-11a859e51290"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 2,  4,  2, 99],\n",
              "       [ 3,  2,  1, 99],\n",
              "       [ 2,  3,  2, 99]])"
            ]
          },
          "execution_count": 39,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JTkqMwJ6Q2ta",
        "outputId": "0708caf3-ac9a-491b-c565-e0ff97aa4244"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "(318, array([  7,   9,   5, 297]), array([107, 105, 106]))"
            ]
          },
          "execution_count": 40,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.sum(data), np.sum(data, axis=0), np.sum(data, axis=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yrzNPmYNQ2ta"
      },
      "source": [
        "**Многие операции реализованы методами ndarray:**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QPeRD5efQ2ta",
        "outputId": "6e571c98-895f-44cb-8900-30cac3aab2c7"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([  7,   9,   5, 297])"
            ]
          },
          "execution_count": 41,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "data.sum(axis=0)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "V4BjhLt0Q2ta",
        "outputId": "f750e316-63a3-4093-fcf3-5d97726c3a3f"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([ 3,  4,  2, 99])"
            ]
          },
          "execution_count": 42,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "data.max(axis=0)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2zfqtmSKQ2ta"
      },
      "outputs": [],
      "source": [
        "#dir(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5k4bP194Q2tb"
      },
      "source": [
        "### Фильтрация данных\n",
        "**Операции сравнения** позволяют создавать фильтры:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gAvn1-3rQ2tb",
        "outputId": "f22f92d9-d9bb-49d1-b367-d487815fc35f"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([0, 1, 2, 3])"
            ]
          },
          "execution_count": 46,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JMItiwcDQ2tb",
        "outputId": "67a78d7d-a23a-41fc-9a1d-cab2f8e1e9fb"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([False, False,  True,  True])"
            ]
          },
          "execution_count": 47,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b>1"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FkynPwtiQ2tb",
        "outputId": "a0672e5e-0548-400f-f13e-3d319a94cc9f"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([ True, False,  True, False])"
            ]
          },
          "execution_count": 48,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b % 2 == 0"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "F8VKwCpQQ2tb",
        "outputId": "6512c67f-b60b-4e23-8ca7-9837492fd10c"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([2, 3])"
            ]
          },
          "execution_count": 49,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b[b > 1]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gPfmO8WMQ2tb",
        "outputId": "3f4283b1-fa1e-40e5-bcc6-b02ef64570d6"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([0, 2])"
            ]
          },
          "execution_count": 50,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "b[b % 2 == 0]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Hwy1jJiWQ2tc",
        "outputId": "b12a6434-dbb6-44fb-8c43-e4d297e98c8f"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([0, 1, 5, 5])"
            ]
          },
          "execution_count": 51,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Можно изменить отфильтрованную часть\n",
        "b[b > 1] = 5\n",
        "b"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-JWyVvQfQ2tc"
      },
      "source": [
        "### Матричные операции"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yaz_YnOWQ2tc",
        "outputId": "9c601ea9-0d1a-47c0-d09c-64843b91b1a9"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[1 2]\n",
            " [3 4]\n",
            " [2 1]]\n",
            "[[ 3 -2]\n",
            " [ 2  1]]\n"
          ]
        }
      ],
      "source": [
        "a = np.array([[1,2],[3,4],[2,1]])\n",
        "b = np.array([[3,-2],[2,1]])\n",
        "print(a,b, sep='\\n')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KTwKpr4lQ2tc",
        "outputId": "78278caf-37c2-4a5d-c01b-7274d6d23e2b"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 7,  0],\n",
              "       [17, -2],\n",
              "       [ 8, -3]])"
            ]
          },
          "execution_count": 53,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Умножение матриц\n",
        "np.dot(a, b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "v1pmE6_6Q2tc",
        "outputId": "2e597d5c-8094-4343-c68d-b74e472e6332"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[1, 3, 2],\n",
              "       [2, 4, 1]])"
            ]
          },
          "execution_count": 54,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Транспонирование\n",
        "a.T"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NESGAH0IQ2td"
      },
      "source": [
        "Матричные операции, в основном, реализованы в модуле linalg пакета numpy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VG_bTzNJQ2td"
      },
      "outputs": [],
      "source": [
        "from numpy import linalg as la"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TI07IBlKQ2td",
        "outputId": "af563cd9-c297-4da5-e10f-c4a3993736d1"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 5, -8],\n",
              "       [ 8, -3]])"
            ]
          },
          "execution_count": 56,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Возведение в степень\n",
        "la.matrix_power(b, 2)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yMrBjdxZQ2td",
        "outputId": "4c9b21f7-6c48-4bd6-cbae-02dea93b8b72"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "6.999999999999999"
            ]
          },
          "execution_count": 57,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Определитель\n",
        "la.det(b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "e64N27pWQ2td"
      },
      "outputs": [],
      "source": [
        "# Обратная матрица\n",
        "c = la.inv(b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "srZe0J-vQ2td",
        "outputId": "77fa1ba3-7f12-4228-80cc-19169300aa37"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[1.00000000e+00, 1.11022302e-16],\n",
              "       [0.00000000e+00, 1.00000000e+00]])"
            ]
          },
          "execution_count": 59,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.dot(c, b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WzV5UngXQ2te",
        "outputId": "fcf5cbd5-e835-48ee-ebfa-dee872f460ec"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 1.00000000e+00,  0.00000000e+00],\n",
              "       [-1.11022302e-16,  1.00000000e+00]])"
            ]
          },
          "execution_count": 60,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "np.dot(b, c)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IWNq6WoBQ2te"
      },
      "source": [
        "## Контрольные вопросы\n",
        "\n",
        "1. Может ли массив ndarray содержать данные различных типов?\n",
        "1. Меняет ли метод reshape форму исходного массива?\n",
        "1. Какой результат даст умножение (*) двумерного массива на число? На одномерный массив?\n",
        "1. Дайте определение операции транспонирования двумерного массива (матрицы)\n",
        "1. Как транспонировать одномерный массив?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qd-GfIjuQ2te"
      },
      "source": [
        "## Задачи для самостоятельного выполнения:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hPFTsg1dQ2te"
      },
      "source": [
        "**Макулатура**. Десять классов школы c 1 по 11, три месяца подряд собирали макулатуру, за каждый месяц известно количество килограмм собранных каждым классом. Три массива формы (10,1). \n",
        "1. Найти суммарное количество собранной школой макулатуры, количество собранной каждым классом макулатуры, среднее количество макулатуры за каждый месяц. \n",
        "2. Если известна стоимость одного кг., найти сумму заработка за каждый месяц; максимальную сумму набранную каким либо классом за один месяц; среднюю сумму по каждому классу. \n",
        "3. Найти количество классов, собравших макулатуры меньше среднего значения.\n",
        "4. Найти величину наибольшего прогресса в последний месяц, по сравнению с предыдущим?\n",
        "\n",
        "*указание* Три массива объединить в один, затем использовать операции библиотеки numpy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "orYdytdWQ2te",
        "outputId": "898d13a3-f64d-43d1-f940-bf20e285e99a"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "##################################\n",
            "array:\n",
            " [[16 42  9 50 42 32 29  5  5 24 46]\n",
            " [23 19 16 44 19  9 39 21 25 11 14]\n",
            " [26 17  2 26 40 17 29 23 34  1  8]]\n",
            "##################################\n",
            "SUM: 763\n",
            "##################################\n",
            "sum №1: 65\n",
            "sum №1: 78\n",
            "sum №1: 27\n",
            "sum №1: 120\n",
            "sum №1: 101\n",
            "sum №1: 58\n",
            "sum №1: 97\n",
            "sum №1: 49\n",
            "sum №1: 64\n",
            "sum №1: 36\n",
            "sum №1: 68\n",
            "##################################\n",
            "avg 1: 27.272727272727273\n",
            "avg 2: 21.818181818181817\n",
            "avg 3: 20.272727272727273\n",
            "##################################\n",
            "mon 1: 2700\n",
            "mon 2: 2160\n",
            "mon 3: 2007\n",
            "##################################\n",
            "MAX: 1080\n",
            "##################################\n",
            "avg №1: 195.0\n",
            "avg №1: 234.0\n",
            "avg №1: 81.0\n",
            "avg №1: 360.0\n",
            "avg №1: 303.0\n",
            "avg №1: 174.0\n",
            "avg №1: 291.0\n",
            "avg №1: 147.0\n",
            "avg №1: 192.0\n",
            "avg №1: 108.0\n",
            "avg №1: 204.0\n",
            "##################################\n",
            "count: 7\n",
            "##################################\n",
            "max: 21\n",
            "##################################\n"
          ]
        }
      ],
      "source": [
        "from random import randint\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "a = np.array([[randint(1,50) for i in range(11)] for j in range(0,3)])\n",
        "print('array:\\n',a)\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "print('SUM:',np.sum(a))\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "maxx=0\n",
        "for i in range(0,11):\n",
        "  tmp=0\n",
        "  tmp+=a[0,i]+a[1,i]+a[2,i]\n",
        "  maxx=max(maxx,tmp)\n",
        "  print('sum №1:',tmp)\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "print('avg 1:',np.average(a[0]))\n",
        "print('avg 2:',np.average(a[1]))\n",
        "print('avg 3:',np.average(a[2]))\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "price=randint(5,10)\n",
        "\n",
        "print('mon 1:', price*np.sum(a[0]))\n",
        "print('mon 2:', price*np.sum(a[1]))\n",
        "print('mon 3:', price*np.sum(a[2]))\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "print('MAX:',maxx*price)\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "for i in range(0,11):\n",
        "  tmp=0\n",
        "  tmp+=a[0,i]+a[1,i]+a[2,i]\n",
        "  print('avg №1:',tmp/3*price)\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "t=[]\n",
        "for i in range(0,11):\n",
        "  tmp=0\n",
        "  tmp+=a[0,i]+a[1,i]+a[2,i]\n",
        "  t.append(tmp)\n",
        "avg=np.average(t)\n",
        "cnt=0\n",
        "for i in t:\n",
        "  if i<avg:\n",
        "    cnt+=1 \n",
        "print('count:',cnt)\n",
        "\n",
        "print('##################################')\n",
        "\n",
        "maxx=0\n",
        "for i in range(0,11):\n",
        "  for j in range(1,3): \n",
        "    maxx=max(maxx,a[j,i]-a[j-1,i])\n",
        "print('max:',maxx)\n",
        "\n",
        "print('##################################')"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.4"
    },
    "colab": {
      "provenance": [],
      "collapsed_sections": [
        "r3GxBNU1Q2tS",
        "hmzddQsVQ2tT",
        "SDj_5LrdQ2tZ",
        "5k4bP194Q2tb",
        "-JWyVvQfQ2tc"
      ],
      "include_colab_link": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}